package com.shsubway.activity.manger;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.czp.library.ArcProgress;
import com.shsubway.R;
import com.shsubway.activity.com.AboutActivity;
import com.shsubway.activity.com.BackActivity;
import com.shsubway.activity.com.MyDateActivity;
import com.shsubway.activity.com.RgisterActivity;
import com.shsubway.activity.staff.RandomActivity;
import com.shsubway.base.BaseActivity;
import com.shsubway.model.GroupEntity;
import com.shsubway.model.ScoreEntity;
import com.shsubway.model.StaffEntity;
import com.shsubway.utils.BigDisMailUtils;
import com.shsubway.utils.Constant;
import com.shsubway.utils.XCRoundImageView;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListener;
import cn.sharesdk.onekeyshare.OnekeyShare;

/**
 * 主页 包含了 站长和职工的管理
 */
public class HomeActivity extends BaseActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.m_make_question)
    ImageView mMakeQuestion;

    @BindView(R.id.nav_view)
    NavigationView navigationView;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawer;
    @BindView(R.id.m_questions)
    ImageView mQuestions;

    @BindView(R.id.radom)
    ImageView radom;
    @BindView(R.id.create_test)
    ImageView crateTest;
    @BindView(R.id.myProgress)
    ArcProgress myProgress;
    @BindView(R.id.right_per)
    TextView rightPer;
    @BindView(R.id.src_score)
    ImageView srcScore;
    @BindView(R.id.my_swf)
    SwipeRefreshLayout mySwf;
    @BindView(R.id.m_staff)
    ImageView mStaff;
    @BindView(R.id.m_group)
    ImageView mGroup;
    @BindView(R.id.score_all)
    ImageView scoreAll;
    private View headerView;
    private LinearLayout layout_header;
    private XCRoundImageView imageViewHeader;
    private TextView user_name;
    private TextView user_post, user_group;
    StaffEntity staffEntity = null;
    Intent intent;
    Bundle bundle;
    public static HomeActivity instance = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        ButterKnife.bind(this);
        instance = this;
        intent = getIntent();
        bundle = intent.getExtras();

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();
        navigationView.setNavigationItemSelectedListener(this);
        initView();
        initEvent();
    }

    private void initEvent() {
        mySwf.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getUserMsg();
                addDate();
            }
        });
    }

    private void initView() {

        setRefresh(mySwf);
        initHeard();
        getUserMsg();
        addDate();
    }

    private void showShare() {

        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间等使用
        oks.setTitle("分享");
        // titleUrl是标题的网络链接，QQ和QQ空间等使用
        oks.setTitleUrl("http://sharesdk.cn");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("#我正在使用XX题库#");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://sharesdk.cn");
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://sharesdk.cn");

        // 启动分享GUI
        oks.show(this);
    }

    private void initHeard() {
        headerView = navigationView.getHeaderView(0);
        layout_header = $(R.id.layout_heard, headerView);
        imageViewHeader = $(R.id.imageView, headerView);
        user_name = $(R.id.user_name, headerView);
        user_post = $(R.id.user_post, headerView);
        user_group = $(R.id.user_group, headerView);
        layout_header.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent.setClass(context, MyDateActivity.class);
                bundle.putSerializable(Constant.STAFFENTITY, staffEntity);
                intent.putExtras(bundle);
                startActivityForResult(intent, 1);
            }
        });
    }

    private void getUserMsg() {
        BmobQuery<StaffEntity> query = new BmobQuery<StaffEntity>();
        query.getObject(String.valueOf(get(Constant.USER_ID, "")), new QueryListener<StaffEntity>() {

            @Override
            public void done(StaffEntity object, BmobException e) {
                if (e == null) {
                    staffEntity = object;
                    Log.e("====", object.toString());
                    user_name.setText(TextUtils.isEmpty(object.getStaff_name()) ? object.getStaff_phone() : object.getStaff_name() + "\n" + object.getStaff_phone());
                    user_post.setText(object.getStaff_post());
                    Picasso.with(context)
                            .load(staffEntity.getStaff_img())
                            .placeholder(object.getStaff_sex() == 0 ? R.mipmap.header_ic : R.mipmap.heard_ic_w)
                            .error(R.mipmap.header_ic)
                            .into(imageViewHeader);
                    BmobQuery<GroupEntity> query = new BmobQuery<GroupEntity>();
                    query.getObject(object.getGroupId(), new QueryListener<GroupEntity>() {
                        @Override
                        public void done(GroupEntity groupEntity, BmobException e) {
                            if (e == null) {
                                if (groupEntity != null) {
                                    user_group.setText(groupEntity.getGroupName());
                                }
                            } else {
                                toast("获取公司信息失败");
                            }
                        }
                    });

                } else {
                    Log.e("E==", e.toString());
                    toast("获取配置信息失败，请联系直属领导。");
                    return;
                }
            }

        });
    }

    private void addDate() {
        BmobQuery<ScoreEntity> query = new BmobQuery<>();
        query.addWhereEqualTo("userId", get(Constant.USER_ID, ""));
        query.setLimit(1000);
        query.findObjects(new FindListener<ScoreEntity>() {
            @Override
            public void done(List<ScoreEntity> list, BmobException e) {
                mySwf.setRefreshing(false);
                if (e == null) {
                    if (list.size() != 0) {
                        ScoreEntity scoreEntity = list.get(list.size() - 1);
                        myProgress.setProgress((int) (scoreEntity.getDanNo() + scoreEntity.getDuoNo() + scoreEntity.getDuoWrongNo() + scoreEntity.getPanNo()));
                        myProgress.setMax(scoreEntity.getDanNoAll() + scoreEntity.getDuoNoAll() + scoreEntity.getPanNoAll());
                        rightPer.setText(BigDisMailUtils.turnTrim(((100 * (scoreEntity.getDanNo() + scoreEntity.getDuoNo() + scoreEntity.getDuoWrongNo() + scoreEntity.getPanNo())) / (scoreEntity.getDanNoAll() + scoreEntity.getDuoNoAll() + scoreEntity.getPanNoAll())), 1));
                        double per = Double.valueOf(rightPer.getText().toString());
                        if (per < 60) {
                            srcScore.setImageResource(R.mipmap.very_low);
                        } else if (per < 80 && per >= 60) {
                            srcScore.setImageResource(R.mipmap.good);
                        } else {
                            srcScore.setImageResource(R.mipmap.very_good);
                        }
                    } else {
                        myProgress.setProgress(100);
                        myProgress.setMax(100);
                        rightPer.setText(BigDisMailUtils.turnTrim(100, 1));
                        srcScore.setImageResource(R.mipmap.very_good);
                    }

                } else {
                    toast("获取配置错误，请联系直属领导。");
                }


            }
        });

    }

    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.home, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        //关于
        if (id == R.id.nav_gallery) {
            bundle.putSerializable(Constant.STAFFENTITY, staffEntity);
            intent.setClass(context, AboutActivity.class);
            intent.putExtras(bundle);
            startActivity(intent);

        } else if (id == R.id.nav_slideshow) {
            bundle.putSerializable(Constant.STAFFENTITY, staffEntity);
            intent.setClass(context, BackActivity.class);
            intent.putExtras(bundle);
            startActivity(intent);

        } else if (id == R.id.nav_manage) {
//            toast("暂未开通");
            //修改密码
            bundle.putSerializable(Constant.STAFFENTITY, staffEntity);
            intent.putExtras(bundle);
            intent.putExtra(Constant.TYPE, 2);
            intent.setClass(context, RgisterActivity.class);
            startActivity(intent);

        } else if (id == R.id.nav_share) {
           /*分享*/
            showShare();
        }
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @OnClick({R.id.m_questions, R.id.m_make_question, R.id.radom, R.id.create_test, R.id.m_staff, R.id.m_group, R.id.score_all})
    public void onClick(View view) {
        bundle.putSerializable(Constant.STAFFENTITY, staffEntity);
        intent.putExtras(bundle);
        switch (view.getId()) {
            case R.id.m_questions:
                startActivity(AllQuestionActivity.class, intent);
                break;
            case R.id.m_make_question:
                //以后这个位置设置三个选项分别为 单选  多远 判断
                if (staffEntity.getStaff_permissions()==1){
                startActivity(MakeQuestionActivity.class, intent);

                }else {
                    toast("暂无权限");
                }

                break;
            case R.id.radom:
                intent.setClass(context,RandomActivity.class);
                startActivityForResult(intent, 1);
                break;
            case R.id.create_test:
                if (staffEntity.getStaff_permissions()==1){

                startActivity(CreateTestActivity.class, intent);
                }else {
                    toast("暂无权限");
                }
                break;
            case R.id.m_staff:
                if (staffEntity.getStaff_permissions()==1){
                intent.setClass(context, ManagementActivity.class);
                startActivityForResult(intent, 1);

                }else {
                    toast("暂无权限");
                }
                break;
            case R.id.m_group:
                if (staffEntity.getStaff_permissions()==1){

                intent.setClass(context, GroupManagerActivity.class);
                startActivityForResult(intent, 1);
                }else {
                    toast("暂无权限");
                }
                break;
            case R.id.score_all:

                if (getIsManager()) {
                    startActivity(TestActivity.class, intent);
                } else {
                    startActivity(ScoreActivity.class, intent);
                }


                break;
        }
    }

    private boolean getIsManager() {
        if (staffEntity.getStaff_permissions() == 1) {
            return true;
        } else {

            return false;
        }
    }

    /**
     * 生成一个可以重复的随机题
     *
     * @param max
     * @param n
     * @return
     */

    private List<Integer> randomList(int max, int n) {
        List<Integer> integers = new ArrayList<>();
        Random random = new Random();
        for (int i = 0; i < n; i++) {
            int randomInt = random.nextInt(max);
            integers.add(randomInt);
        }
        return integers;
    }


    /**
     * 随机指定范围内N个不重复的数
     * 利用HashSet的特征，只能存放不同的值
     *
     * @param min          指定范围最小值
     * @param max          指定范围最大值
     * @param n            随机数个数
     * @param set<Integer> set 随机数结果集
     */
    public static void randomSet(int min, int max, int n, HashSet<Integer> set) {
        if (n > (max - min + 1) || max < min) {
            return;
        }
        for (int i = 0; i < n; i++) {
            // 调用Math.random()方法
            int num = (int) (Math.random() * (max - min)) + min;
            set.add(num);// 将不同的数存入HashSet中
        }
        int setSize = set.size();
        // 如果存入的数小于指定生成的个数，则调用递归再生成剩余个数的随机数，如此循环，直到达到指定大小
        if (setSize < n) {
            randomSet(min, max, n - setSize, set);// 递归
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 1) {
            getUserMsg();
            addDate();
        }
    }
}
